package com.zyq.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zyq.common.entity.AclUser;
import com.zyq.security.utils.WebUtils;
import com.zyq.system.dao.AclUserDao;
import com.zyq.system.service.AclUserService;
import com.zyq.common.util.JWTUtil;
import com.zyq.common.vo.Result;
import com.zyq.system.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

@Service
public class AclUserServiceImpl implements AclUserService {
    @Autowired
    private AclUserDao aclUserDao;
    @Override
    public Result<AclUser> getUserInfoByUsername(String username) {
        QueryWrapper<AclUser> owq = new QueryWrapper<>();
        owq.eq("username",username);
        owq.eq("is_deleted",0);

        AclUser aclUser = aclUserDao.selectOne(owq);

        if(aclUser != null){
            return new Result<AclUser>(200,"用户信息查询成功",aclUser);
        }
        return new Result<AclUser>(500,"用户信息查询失败",new AclUser());
    }

    @Override
    public Result<AclUser> getInfoFromToken() {
        String token = WebUtils.getRequest().getHeader("token");
        Map<String, Object> tokenChaim = JWTUtil.getTokenChaim(token);
        String username = (String) tokenChaim.get("username");

        QueryWrapper<AclUser> aclUserQueryWrapper = new QueryWrapper<>();
        aclUserQueryWrapper.eq("username",username);
        aclUserQueryWrapper.eq("is_deleted",0);

        AclUser aclUser = aclUserDao.selectOne(aclUserQueryWrapper);

        return new Result<>(200,"查询成功",aclUser);
    }

    @Override
    public Result<IPage<AclUser>> getUserByPage(Integer currentPage, Integer pageSize, UserVo userVo) {
        IPage<AclUser> page = new Page<>(currentPage,pageSize);

        QueryWrapper<AclUser> aclUserQueryWrapper = new QueryWrapper<>();
        if(StringUtils.hasText(userVo.getUsername())){
            aclUserQueryWrapper.like("username",userVo.getUsername());
        }

        if(StringUtils.hasText(userVo.getStartDate())){
            aclUserQueryWrapper.ge("gmt_create",userVo.getStartDate());
        }

        if(StringUtils.hasText(userVo.getEndDate())){
            aclUserQueryWrapper.le("gmt_modified",userVo.getEndDate());
        }

        IPage<AclUser> page1 = aclUserDao.selectPage(page, aclUserQueryWrapper);

        return new Result<>(200,"查询用户管理成功",page1);
    }
}
